package ddn.dao.hibernate.generic;


import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

/**
 * Generated at Mon May 10 12:58:06 CEST 2010
 *
 * @author Salto-db Generator v1.0.16 / EJB3 + Spring/Hibernate DAO + TestCases
 * @see http://www.hibernate.org/328.html
 */
public abstract class AbstractHibernateDAO<T, ID extends Serializable> extends HibernateDaoSupport implements GenericDAO<T, ID> {

	protected final Log log =  LogFactory.getLog(this.getClass().getName());
	private Class<T> persistentClass;

	public AbstractHibernateDAO() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public Class<T> getPersistentClass() {
        return persistentClass;
    }

	@SuppressWarnings("unchecked")
	public T getById(ID id) {
		return (T) getSession().get(getPersistentClass(), id);
	}

	@SuppressWarnings("unchecked")
	public T getById(ID id, boolean lock) {
		if (lock) {
			return (T) getSession().get(getPersistentClass(), id,
					LockMode.UPGRADE);
		} else
			return getById(id);
	}

	@SuppressWarnings("unchecked")
	public T loadById(ID id) {
		return (T) getSession().load(getPersistentClass(), id);
	}

	@Transactional
	public void save(T entity) {
            log.info("Enters save");
		if (entity instanceof UpdatablePojo){			
			UpdatablePojo o = (UpdatablePojo)entity;
			Timestamp t = new Timestamp(System.currentTimeMillis());
			o.setCreationDate(t);
			o.setUpdateDate(t);
		}
				
		this.getSession(true).save(entity);                
	}

	@Transactional
	public void update(T entity) {
		//getSession().update(entity);
		
		if (entity instanceof UpdatablePojo){			
			UpdatablePojo o = (UpdatablePojo)entity;
			o.setUpdateDate(new Timestamp(System.currentTimeMillis()));
		}
		
		this.getHibernateTemplate().update(entity);
	}

	@Transactional
	public void saveOrUpdate(T entity) {
		
		if (entity instanceof UpdatablePojo){		
			UpdatablePojo o = (UpdatablePojo)entity;
			Timestamp t = new Timestamp(System.currentTimeMillis());
			if (o.getCreationDate()==null){
				o.setCreationDate(t);
			}			
			o.setUpdateDate(t);
		}
		getSession(true).saveOrUpdate(entity);
	}

	@Transactional
	public void delete(T entity) {
		//getSession().delete(entity);
		this.getHibernateTemplate().delete(entity);
	}

	@Transactional
	public void deleteById(ID id) 	{
		//getSession().delete(loadById(id));
		
		this.getHibernateTemplate().delete(loadById(id));
	}

	@SuppressWarnings("unchecked")
    public List<T> findAll() {
        return findByCriteria();
    }
	
	/**
     * Use this inside subclasses as a convenience method.
     */
	 @SuppressWarnings("unchecked")
	    protected List<T> findByCriteria(Criterion... criterion) {
	        Criteria crit = getSession().createCriteria(getPersistentClass());
	        for (Criterion c : criterion) {
	        	if(c != null){
	        		crit.add(c);
	        	}
	        }
	        return crit.list();
	   }
	/**
	 * 
	 * Filter and order
	 */
	@SuppressWarnings("unchecked")
    protected List<T> findByCriteria(String order, String orderField,Criterion... criterion) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
        	if(c != null){
        		crit.add(c);
        	}
        }
        if(order.equals("asc")){
        	crit.addOrder(Order.asc(orderField));
        }else{
        	if (order.equals("desc")){
        		crit.addOrder(Order.desc(orderField));
        	}
        }
        return crit.list();
   }
   
	/**
	 * 
	 * Filter and limited
	 */
	@SuppressWarnings("unchecked")
    protected List<T> findByCriteria(Integer count,String orderField,Criterion... criterion) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
        	if(c != null){
        		crit.add(c);
        	}
        }
        crit.setMaxResults(count);
       
        if (!orderField.equals("")){
	        crit.addOrder(Order.desc(orderField));
        }
        return crit.list();
   }
    
   	/**
 	 * Find by criteria.
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Map criterias) {
	
		Criteria criteria = getSession().createCriteria(getPersistentClass());
		criteria.add(Restrictions.allEq(criterias));
		return criteria.list();
	}
	
	/**
	 * This method will execute an HQL query and return the number of affected entities.
	 */
	protected int executeQuery(String query, String namedParams[],	Object params[]) {
		Query q = getSessionFactory().openSession().createQuery(query);
		//Query q = getSession().createQuery(query);
		
		if (namedParams != null) {
			for (int i = 0; i < namedParams.length; i++) {
				q.setParameter(namedParams[i], params[i]);
			}
		}

		return q.executeUpdate();
	}
	
	protected int executeQuery(String query) {
		return executeQuery(query, null, null);
	}
	
	/**
	 * This method will execute a Named HQL query and return the number of affected entities.
	 */
	protected int executeNamedQuery(String namedQuery, String namedParams[],	Object params[]) {
		Query q = getSession().getNamedQuery(namedQuery);
		
		if (namedParams != null) {
			for (int i = 0; i < namedParams.length; i++) {
				q.setParameter(namedParams[i], params[i]);
			}
		}

		return q.executeUpdate();
	}
	
	protected int executeNamedQuery(String namedQuery) {
		return executeNamedQuery(namedQuery, null, null);
	}
	
	@SuppressWarnings("unchecked")
    public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        Example example =  Example.create(exampleInstance).excludeZeroes().enableLike().ignoreCase();
        for (String exclude : excludeProperty) {
            example.excludeProperty(exclude);
        }
        crit.add(example);
        return crit.list();
    }

	public List<T> findByCriteriaDisjunction(Disjunction disjunction){
	    Criteria crit = getSession().createCriteria(getPersistentClass());
	    crit.add(disjunction);
        return crit.list();    
    }
    
}
